/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.permission.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.commond.State;
import com.legendshop.framework.commond.StateImpl;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.ApplicationEnum;
import com.legendshop.oa.constants.CommonPage;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.exception.BusinessException;
import com.legendshop.oa.exception.ErrorCodes;
import com.legendshop.oa.model.Role;
import com.legendshop.oa.model.User;
import com.legendshop.oa.model.UserRole;
import com.legendshop.oa.model.UserRoleId;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.permission.form.UserRoleForm;
import com.legendshop.permission.form.UsersForm;
import com.legendshop.permission.page.SecurityBackPage;
import com.legendshop.permission.page.SecurityFowardPage;
import com.legendshop.permission.page.SecurityRedirectPage;
import com.legendshop.permission.page.SecurityTilesPage;
import com.legendshop.permission.service.AdminUserService;
import com.legendshop.permission.service.RightDelegate;
import com.legendshop.util.AppUtils;

/**
 * UserAdminController.
 */
@Controller
@RequestMapping("/admin/member/user")
public class UserAdminController extends BaseController {
	
	/** The log. */
	private final static Logger log = LoggerFactory.getLogger(UserAdminController.class);

	/** The basket service. */
	@Autowired
	private RightDelegate rightDelegate;
	
	
	/**
	 * 管理员服务器
	 */
	@Autowired
	private AdminUserService adminUserService;

	/**
	 * Delete user role by user id.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param userRoleForm
	 *            the user role form
	 * @return the string
	 */
	@RequestMapping("/deleteUserRoleByUserId")
	public String deleteUserRoleByUserId(HttpServletRequest request, HttpServletResponse response, UserRoleForm userRoleForm,String appNo) {
		String userId = request.getParameter("userId");
		log.info("Action deleteUserRoleByUserId with userId  " + userId);
		
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		
		List<UserRole> userRoles = new ArrayList<UserRole>();
		String[] strArray = userRoleForm.getStrArray();
		for (String element : strArray) {
			UserRole userRole = new UserRole();
			UserRoleId userRoleId = new UserRoleId();
			userRoleId.setUserId(Long.parseLong(userId));
			userRoleId.setAppNo(appNo);
			userRoleId.setRoleId(Long.parseLong(element));
			userRole.setId(userRoleId);
			userRoles.add(userRole);
		}
		State state = new StateImpl();

		rightDelegate.deleteRoleFromUser(userRoles, state);

		request.setAttribute("userId", userId);
		return PathResolver.getPath(request, response, SecurityRedirectPage.FIND_USER_ROLES.getNativeValue() + "/" + userId + "?appNo=" + appNo,
				SecurityRedirectPage.FIND_USER_ROLES);
	}

	/**
	 * Save user.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param usersForm
	 *            the users form
	 * @return the action forward
	 */
	@RequestMapping("/saveUser")
	public String saveUser(HttpServletRequest request, HttpServletResponse response, UsersForm usersForm) {
		State state = new StateImpl();
		User user = usersForm.getUser();
		if (rightDelegate.isUserExist(user.getName(), state)) {
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}

		Long id = rightDelegate.saveUser(user, state);
		log.info("success saveUser,id = " + id);

		return PathResolver.getPath(request, response, SecurityFowardPage.USERS_LIST);
	}


	/**
	 * Update user status.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param usersForm
	 *            the users form
	 * @return the action forward
	 */
	@RequestMapping("/updateUserStatus")
	public String updateUserStatus(HttpServletRequest request, HttpServletResponse response, UsersForm usersForm) {
		log.debug("UserAction updateUserStatus");
		User user = usersForm.getUser();
		String enabled = user.getEnabled();
		Long userId = user.getId();

		State state = new StateImpl();

		User olduser = rightDelegate.findUserById(userId, state);
		olduser.setEnabled(enabled);
		olduser.setNote(user.getNote());
		rightDelegate.updateUser(olduser, state);
		return PathResolver.getPath(request, response, SecurityFowardPage.USERS_LIST);
	}

	/**
	 * Preupdate status.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the action forward
	 */
	@Deprecated
	@RequestMapping("/preupdateStatus")
	public String preupdateStatus(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.info("Action preupdateStatus with id  " + id);
		State state = new StateImpl();
		User user = rightDelegate.findUserById(Long.parseLong(id), state);
		request.setAttribute("user", user);
		return PathResolver.getPath(request, response, SecurityBackPage.UPDATE_USER_STATUS);
	}

	/**
	 * Update user passowrd.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param usersForm
	 *            the users form
	 * @return the action forward
	 */
	@RequestMapping("/updateUserPassowrd")
	public String updateUserPassowrd(HttpServletRequest request, HttpServletResponse response, UsersForm usersForm) {
		log.info("UserAction updateUserById");
		User user = usersForm.getUser();
		String passwordag = user.getPasswordag();
		if ((user.getPassword() == null) || (user.getPassword() == "")) {
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}
		if (!passwordag.endsWith(user.getPassword())) {// 2次密码要相等
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}
		State state = new StateImpl();
		rightDelegate.updateUserPassowrd(user.getId(), user.getPassword(), state);
		return PathResolver.getPath(request, response, SecurityFowardPage.USERS_LIST);
	}

	/**
	 * Find user by id.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the action forward
	 */
	@RequestMapping("/findUserById")
	public String findUserById(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		log.info("Action findUserById with id  " + id);

		State state = new StateImpl();
		User user = rightDelegate.findUserById(Long.parseLong(id), state);
		request.setAttribute("user", user);

		return PathResolver.getPath(request, response, SecurityBackPage.UPDATE_USER_PASSWORD);
	}

	/**
	 * Save role to user.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param usersForm
	 *            the users form
	 * @return the action forward
	 */
	@RequestMapping("/saveRoleToUser")
	public String saveRoleToUser(HttpServletRequest request, HttpServletResponse response, UsersForm usersForm) {
		String userId = request.getParameter("userId");
		String appNo = request.getParameter("appNo");
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		
		List<UserRole> userRoles = new ArrayList<UserRole>();
		String[] strArray = usersForm.getStrArray();
		for (String element : strArray) {
			UserRole userRole = new UserRole();
			UserRoleId userRoleId = new UserRoleId();
			userRoleId.setRoleId(Long.parseLong(element));
			userRoleId.setUserId(Long.parseLong(userId));
			userRoleId.setAppNo(appNo);
			userRole.setId(userRoleId);
			userRoles.add(userRole);
		}

		State state = new StateImpl();
		rightDelegate.saveRolesToUser(userRoles, state);
		return PathResolver.getPath(request, response, SecurityRedirectPage.FIND_USER_ROLES.getNativeValue() + "/" + userId + "?appNo=" + appNo,
				SecurityRedirectPage.FIND_USER_ROLES);
	}

	/**
	 * Find other role by user.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the action forward
	 */
	@RequestMapping("/findOtherRoleByUser")
	public String findOtherRoleByUser(HttpServletRequest request, HttpServletResponse response,String appNo) {
		if(AppUtils.isBlank(appNo)){
			throw new BusinessException("appNo is missing");
		}
		
		String curPageNO = request.getParameter("curPageNO");
		String userIds = request.getParameter("userId");
		Long userId = userIds == null ? 0 :Long.parseLong(userIds);
		

		State state = new StateImpl();
		PageSupport<Role> ps = rightDelegate.findOtherRoleByUser(curPageNO,userId , appNo, state);
		PageSupportHelper.savePage(request, ps);
		
		//装载用户
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			request.setAttribute("user", rightDelegate.findUserById(userId, state));
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			request.setAttribute("user", adminUserService.getAdminUser(userId));
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}

		return PathResolver.getPath(request, response, SecurityBackPage.FIND_OTHER_ROLE_BY_USER);
	}

	/**
	 * Find function by user.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the action forward
	 */
	@RequestMapping("/findFunctionByUser")
	public String findFunctionByUser(HttpServletRequest request, HttpServletResponse response, String appNo) {
		String userIds = request.getParameter("userId");
		Long userId = userIds == null ? 0 :Long.parseLong(userIds);
		log.info("UserAction findFunctionByUser : " + userId);
		State state = new StateImpl();
		User user = rightDelegate.findUserById(userId, state);
		List functions = rightDelegate.findFunctionByUser(userId, appNo, state);
		request.setAttribute("functions", functions);
		request.setAttribute("user", user);

		return PathResolver.getPath(request, response, SecurityBackPage.FIND_FUNCTION_BY_USER);
	}

	/**
	 * Users list.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @param curPageNO
	 *            the cur page no
	 * @return the action forward
	 */
	@RequestMapping("/usersList")
	public String usersList(HttpServletRequest request, HttpServletResponse response, String curPageNO) {
		String userName = UserManager.getUserName(request);
		if (userName == null) {
			throw new BusinessException("not login yet", ErrorCodes.BUSINESS_ERROR);
		}
		String name = request.getParameter("search") == null ? "" : request.getParameter("search");//搜索内容
		String enabled = request.getParameter("enabled") == null ? "" : request.getParameter("enabled");

		State state = new StateImpl();
		PageSupport<User> ps = rightDelegate.findAllUser(curPageNO, name, enabled, state);
		PageSupportHelper.savePage(request, ps);
		
		request.setAttribute("name", name);
		request.setAttribute("enabled", enabled);

		return PathResolver.getPath(request, response, SecurityBackPage.USER_LIST_PAGE);
	}

	/**
	 * Find role by user.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the action forward
	 */
	@RequestMapping("/findRoleByUser")
	public String findRoleByUser(HttpServletRequest request, HttpServletResponse response) {
		String userIds = request.getParameter("userId");
		Long userId = userIds == null ? 0 :Long.parseLong(userIds);
		String appNo = request.getParameter("appNo");
		log.info("UserAction findOtherRoleByUser : " + userId);
		State state = new StateImpl();
		User user = rightDelegate.findUserById(userId, state);
		List roles = rightDelegate.findRoleByUser(userId, appNo,  state);
		request.setAttribute("roles", roles);
		request.setAttribute("user", user);

		return PathResolver.getPath(request, response, SecurityBackPage.FIND_ROLE_BY_USER_PAGE);
	}

	// new interface

	/**
	 * Load.
	 * 
	 * @param request
	 *            the request
	 * @param response
	 *            the response
	 * @return the string
	 */

	@RequestMapping(value = "/load")
	public String load(HttpServletRequest request, HttpServletResponse response) {
		return PathResolver.getPath(request, response, SecurityBackPage.MODIFY_USER);
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) {
		return null;
	}

	@RequestMapping("/query")
	public String query(HttpServletRequest request, HttpServletResponse response, String curPageNO, User user) {

		String userName = UserManager.getUserName(request);
		if (userName == null) {
			throw new BusinessException("not login yet", ErrorCodes.UNAUTHORIZED);
		}
		String name = user.getName();
		String enabled = user.getEnabled();
		State state = new StateImpl();
		PageSupport<User> ps = rightDelegate.findAllUser(curPageNO, name,enabled, state);
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("bean", user);

		return PathResolver.getPath(request, response, SecurityTilesPage.USER_LIST_PAGE);
	}

	@RequestMapping(value = "/save")
	public String save(HttpServletRequest request, HttpServletResponse response, User user) {
		State state = new StateImpl();

		if (rightDelegate.isUserExist(user.getName(), state)) {
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}

		Long id = user.getId();

		if (id == null) {
			id = rightDelegate.saveUser(user, state);
		} else {
			rightDelegate.updateUser(user, state);
		}
		log.info("success saveUser,id = " + id);

		return PathResolver.getPath(request, response, SecurityFowardPage.USERS_LIST);
	}

	@RequestMapping(value = "/updatePassword")
	public String updatePassword(HttpServletRequest request, HttpServletResponse response, User user, String appNo) {

		log.info("UserAction updateUserById");
		String passwordag = user.getPasswordag();
		if ((user.getPassword() == null) || (user.getPassword() == "" || user.getPassword().length() < 6)) {
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}
		if (!passwordag.equals(user.getPassword())) {// 2次密码要相等
			return PathResolver.getPath(request, response, CommonPage.ERROR_PAGE);
		}
		State state = new StateImpl();
		//更新密码
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			rightDelegate.updateUserPassowrd(user.getId(), user.getPassword(),  state);
			return PathResolver.getPath(request, response, SecurityRedirectPage.USERINFO_LIST);//更新普通用户密码
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			adminUserService.updateAdminUserPassword(user.getId(),user.getPassword());//更新管理员密码
			return PathResolver.getPath(request, response, SecurityRedirectPage.ADMIN_USERS_LIST);
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}

	}

	@RequestMapping(value = "/update/{id}")
	public String update(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, String appNo) {
		log.info("Action findUserById with id  " + id);
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		State state = new StateImpl();
		//装载用户
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			request.setAttribute("bean", rightDelegate.findUserById(id, state));
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			request.setAttribute("bean", adminUserService.getAdminUser(id));
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}
		return PathResolver.getPath(request, response, SecurityTilesPage.UPDATE_USER_PASSWORD);
	}

	@RequestMapping(value = "/roles/{id}")
	public String roles(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, String appNo) {
		log.info("UserAction findOtherRoleByUser : " + id);
		State state = new StateImpl();
		
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		
		List roles = rightDelegate.findRoleByUser(id, appNo, state);
		request.setAttribute("list", roles);
		
		//装载用户
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			request.setAttribute("bean", rightDelegate.findUserById(id, state));
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			request.setAttribute("bean", adminUserService.getAdminUser(id));
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}
		request.setAttribute("appNo", appNo);
		return PathResolver.getPath(request, response, SecurityTilesPage.FIND_ROLE_BY_USER_PAGE);
	}

	@RequestMapping(value = "/otherRoles/{id}")
	public String otherRoles(HttpServletRequest request, HttpServletResponse response, String curPageNO, @PathVariable Long id, String appNo) {
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		State state = new StateImpl();
		PageSupport<Role> ps = rightDelegate.findOtherRoleByUser(curPageNO, id, appNo, state);
		PageSupportHelper.savePage(request, ps);
		//装载用户
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			request.setAttribute("bean", rightDelegate.findUserById(id, state));
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			request.setAttribute("bean", adminUserService.getAdminUser(id));
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}

		return PathResolver.getPath(request, response, SecurityTilesPage.FIND_OTHER_ROLE_BY_USER);
	}

	@Deprecated
	@RequestMapping(value = "/deleteRoles/{id}")
	public String deleteRoles(HttpServletRequest request, HttpServletResponse response, String[] strArray, @PathVariable Long id) {

		log.info("Action deleteUserRoleByUserId with userId  " + id);
		List<UserRole> userRoles = new ArrayList<UserRole>();
		for (String element : strArray) {
			UserRole userRole = new UserRole();
			UserRoleId userRoleId = new UserRoleId();
			userRoleId.setUserId(id);
			userRoleId.setRoleId(Long.parseLong(element));
			userRole.setId(userRoleId);
			userRoles.add(userRole);
		}
		State state = new StateImpl();
		rightDelegate.deleteRoleFromUser(userRoles, state);
		return PathResolver.getPath(request, response, SecurityFowardPage.FIND_ROLE_BY_USER);
	}

	@RequestMapping(value = "/functions/{id}")
	public String functions(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, String appNo) {
		log.info("UserAction findFunctionByUser : " + id);
		if(!ApplicationEnum.instance(appNo)){
			throw new BusinessException( "appNo is missing");
		}
		State state = new StateImpl();
		List functions = rightDelegate.findFunctionByUser(id, appNo, state);
		request.setAttribute("list", functions);
		//装载用户
		if(ApplicationEnum.FRONT_END.value().equals(appNo)){
			request.setAttribute("bean", rightDelegate.findUserById(id, state));
		}else if(ApplicationEnum.BACK_END.value().equals(appNo)){
			request.setAttribute("bean", adminUserService.getAdminUser(id));
		}else{
			throw new BusinessException(appNo + " appNo incorrect");
		}


		return PathResolver.getPath(request, response, SecurityTilesPage.FIND_FUNCTION_BY_USER);
	}
	
	/**
	 * 检查用户是否存在
	 * @param userName
	 * @return
	 */
	@RequestMapping("/isUserNameExist")
	public @ResponseBody boolean isUserNameExist(String userName){
		return adminUserService.isUserExist(userName);
	}

}
